package com.huiquan.sphinx;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.joda.time.DateTime;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;

public class ElasticSearchToolsTest {


    //elasticsearch2.3的客户端实例
    static Client client = null;

    static {
        try {
            //初始化连接客户端
            client = TransportClient.builder().build()
                    .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9200));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /****
     * 测试读取仅仅索引没有存储的字段，从倒排里面加载数据
     * 过滤数据
     */
    public static void filterQueryString() {
        //构建查询请求
        SearchRequestBuilder sbuilder = client.prepareSearch("testvocabularyandsentence") // index name
                .setTypes("testvocabularyandsentence") // type name
                .setQuery(QueryBuilders.termQuery("vocabulary", "B超")) // Query
//.setPostFilter(QueryBuilders.rangeQuery("eventCount").from(1).to(18))   // Filter
                .setFrom(0).setSize(20).setExplain(true);

        System.out.println(sbuilder.toString());

        SearchResponse response = sbuilder.execute().actionGet();

        System.out.println(response.toString());

    }


    public static void main(String[] args) throws Exception {

        //单个聚合字段，支持.写法
//        testOneAggString(aggField);
        filterQueryString();
        client.close();

    }
}